//
//  WYEditHomePageController.m
//  Boss
//
//  Created by admin on 2018/7/5.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYEditHomePageController.h"
#import "WYPersonMessageHeaderCell.h"
#import "WYPersonMessageCell.h"
#import "WYEditSectionView.h"
#import "WYEnterpriseCell.h"
#import "WYEditMessageController.h"
 #import "WYIndustryController.h"
#import "CZHAddressPickerView.h"
#import "WYDataPicker.h"
#import "WYEnterPriserIntroductionController.h"
#import "WYProductCell.h"
#import "WYHonorCell.h"
#import "WYAddProductController.h"
#import "WYUploadModel.h"
#import "WYEditUserMessage.h"
#import "UIImage+WYSaveImage.h"
#import "WYDeleteHonorController.h"
#import "WYEditProductController.h"
//#import <math.h>
@interface WYEditHomePageController ()<UITableViewDelegate,UITableViewDataSource,WYEditSectionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,WYHonorCellDelegate>
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic, copy) NSString *province;

@property (nonatomic, copy) NSString *city;

@property (nonatomic, copy) NSString *area;

@property (nonatomic,strong)  WYDataPicker *datePicker;

@property (nonatomic,strong)NSString *date;

@property (nonatomic,strong)NSString *pathString;

@property (nonatomic,strong)WYUploadModel *model;

@property (nonatomic,strong)WYEditUserMessage *editMessage;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSArray *nameArray;

@property (nonatomic,strong)NSMutableArray *honorArray;

@property (nonatomic,assign)BOOL isRefresh;
@property (nonatomic,assign)BOOL isLogo;
@end

@implementation WYEditHomePageController

-(NSMutableArray *)honorArray
{
    if (!_honorArray) {
        _honorArray = [[NSMutableArray alloc]init];
    }
    return _honorArray;
}




-(NSArray *)nameArray
{
    if (!_nameArray) {
        _nameArray = @[@"企业LOGO",@"企业简称",@"当前职位",@"所属行业",@"所在地区",@"创立时间",@"企业简介"];
    }
    return _nameArray;
    
    
}
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        
    }
    self.isRefresh = YES;
    [self loadData];
    [self loadProductData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didChangeHeightWithHonor:) name:@"didChangeHeight" object:nil];
}
-(void)loadProductData
{
    WEAKSELF
    [WYHttpServer getProductServiceWithCurrentPage:@"1" WithPageSize:@"10" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            if (weakSelf.isRefresh) {
                [weakSelf.dataArray removeAllObjects];
            }
            
            NSArray *array =[WYProductService getProductArrayFromJson:response[@"result"][@"detail"]];
            if (array.count) {
                [weakSelf.dataArray addObjectsFromArray:array];
            }
            [weakSelf.tableView reloadData];
            
        }
    }];
}




-(void) loadData
{
    WEAKSELF
    [WYHttpServer getHomePageUserMessageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
       
        if (success) {
            weakSelf.editMessage = [WYEditUserMessage getEditModelFromJson:response[@"result"]];
             [weakSelf.honorArray removeAllObjects];
            if (weakSelf.editMessage.companyHonor.length) {
                NSArray *array = [weakSelf.editMessage.companyHonor componentsSeparatedByString:@","];
                if (array.count) {
                    [weakSelf.honorArray addObjectsFromArray:array];
                }
            }
            [weakSelf.tableView reloadData];
        }
    }];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
    
    
}

-(void)setupUI
{
    self.navigationItem.title = @"编辑主页";
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WYPersonMessageHeaderCell" bundle:nil] forCellReuseIdentifier:@"WYPersonMessageHeaderCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYEnterpriseCell" bundle:nil] forCellReuseIdentifier:@"WYEnterpriseCell"];
    self.tableView.estimatedRowHeight = 60;
    [self.tableView registerNib:[UINib nibWithNibName:@"WYProductCell" bundle:nil] forCellReuseIdentifier:@"WYProductCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYHonorCell" bundle:nil] forCellReuseIdentifier:@"WYHonorCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    WYDataPicker *datePicker = [[WYDataPicker alloc]initWithFrame:CGRectMake(0, kScreenHeight-214, kScreenWidth, 214)];
    WEAKSELF
    datePicker.complete = ^(NSString *date) {
        //        weakSelf.ageLabel.text =[NSString stringWithFormat:@"%.0f",[weakSelf calculateAge:date]];
        weakSelf.date = date;
        [weakSelf editTime];
    };
    [self.view addSubview:datePicker];
    datePicker.hidden = YES;
    self.datePicker = datePicker;
    
    
    
}
-(void)editTime
{
    WEAKSELF
    [WYHttpServer editComPanyTimeWithTime:self.date SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }
    }];
    
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 4;
    }
    if (section==1) {
        return 3;
    }
    if (section==3) {
        
        return self.honorArray.count ? 1:0;
    }
    if (section==4) {
        return self.dataArray.count;
    }
    
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0&&indexPath.section==0) {
        WYPersonMessageHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYPersonMessageHeaderCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = self.nameArray[indexPath.row];
        [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",self.editMessage.companyUrl]] placeholderImage:nil];
        
        return cell;
    }
    if (indexPath.section==0||indexPath.section==1) {
        WYEnterpriseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYEnterpriseCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"WYEnterpriseCell" owner:nil options:nil].firstObject;
        }
        if (indexPath.section==0) {
            cell.leftName.text = self.nameArray[indexPath.row];
            if (indexPath.row==1) {
                if (self.editMessage.companyName.length) {
                    cell.detailName.text = self.editMessage.companyName;
                }
            }
            if (indexPath.row==2) {
                if (self.editMessage.duty.length) {
                    cell.detailName.text = self.editMessage.duty;
                }
            }
            if (indexPath.row==3) {
                if (self.editMessage.profession.length) {
                    cell.detailName.text = self.editMessage.profession;
                }
            }
            
            
            
        }else{
            if (indexPath.row==0) {
                if (self.editMessage.companyAddress.length) {
                    cell.detailName.text = self.editMessage.companyAddress;
                }
            }
            if (indexPath.row==1) {
                if (self.editMessage.registerTime.length) {
                    cell.detailName.text = self.editMessage.registerTime;
                }
            }
            if (indexPath.row==2) {
                if (self.editMessage.companyIntro.length) {
                    cell.detailName.text = self.editMessage.companyIntro;
                    cell.detailName.numberOfLines = 3;
                }
            }
            
            
            cell.leftName.text = self.nameArray[indexPath.row+4];
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if (indexPath.section==4) {
        WYProductCell *cell =[tableView dequeueReusableCellWithIdentifier:@"WYProductCell" forIndexPath:indexPath];
        if (!cell) {
            cell =[[NSBundle mainBundle]loadNibNamed:@"WYProductCell" owner:nil options:nil].firstObject;
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        WYProductService *service = self.dataArray[indexPath.row];
        [cell setService:service];
        return cell;
    }
    if (indexPath.section==3) {
        WYHonorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYHonorCell" forIndexPath:indexPath];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.honorArray;
        cell.delegate = self;
        return cell;
    }
    
    
    
    
    WYEnterpriseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYEnterpriseCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"WYEnterpriseCell" owner:nil options:nil].firstObject;
    }
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0.00001;
    }
    if (section==1) {
        return 0;
    }
    if (section==3) {
        return 50;
    }
    if (section==4) {
        return 50;
    }
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==3) {
        WYEditSectionView *esc = [[WYEditSectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        esc.index = 3;
        esc.delegate = self;
        esc.backgroundColor = [UIColor whiteColor];
        if (self.honorArray.count) {
            esc.lineView.hidden = YES;
        }
        return esc;
        
    }
    if (section==4) {
        WYEditSectionView *esc = [[WYEditSectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        esc.delegate = self;
        esc.index = 4;
        esc.backgroundColor = [UIColor whiteColor];
        if (self.dataArray.count) {
            esc.lineView.hidden = YES;
        }
        return esc;
    }
    
    
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = kColore2e2e2;
    return view;
}
-(void)didSelectImageViewWithImage:(UIImage *)image WithImageUrl:(NSString *)url WithDataArray:(NSArray *)dataArray WithIndex:(NSIndexPath *)indexPath
{
    WYDeleteHonorController *dvc = [[WYDeleteHonorController alloc]init];
    dvc.image = image;
    dvc.imageUrl = url;
    dvc.dataArray = dataArray;
    dvc.indexPath = indexPath;
    dvc.isShowDelete = YES;
    [self.navigationController pushViewController:dvc animated:YES];
}


-(void)didSelectAddButton:(NSUInteger)index WithBtn:(UIButton *)btn
{
    if (index==3) {
        
        
        NSLog(@"%ld",index);
       
        self.isLogo  = NO;
        [self alertImagePickerWithCell:nil WithView:btn];
        
        
        
        
        
        
        
        
    }else{
        WYAddProductController *apc = [[WYAddProductController alloc]init];
        [self.navigationController pushViewController:apc animated:YES];
    }
}
-(void)alertImagePickerWithCell:(WYPersonMessageHeaderCell *)cell WithView:(UIButton *)btn
{
    WEAKSELF
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    if (IS_IPAD) {
        UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
        if (btn) {
            popPresenter.sourceView = btn;
            popPresenter.sourceRect = btn.bounds;
        }else{
            popPresenter.sourceView = cell;
            popPresenter.sourceRect = cell.bounds;
        }
        
       
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0&&indexPath.section==0) {
        self.isLogo = YES;
        WYPersonMessageHeaderCell *cell =[tableView cellForRowAtIndexPath:indexPath];
        
        
        [self alertImagePickerWithCell:cell WithView:nil];
        
        
        
        
    }
    
    
    if (indexPath.section==0) {
        if (indexPath.row==1) {
            WYEditMessageController *evc = [[WYEditMessageController alloc]init];
            evc.placeHoder = @"请输入公司简称";
            evc.navTitle = @"企业简称";
            evc.tag = indexPath.row;
            evc.textFieldText = self.editMessage.companyName;
            [self.navigationController pushViewController:evc animated:YES];
        }
        if (indexPath.row==2) {
            WYEditMessageController *evc = [[WYEditMessageController alloc]init];
            evc.placeHoder = @"请输入当前职位";
            evc.navTitle = @"当前职位";
            evc.tag = indexPath.row;
            evc.textFieldText = self.editMessage.duty;
            [self.navigationController pushViewController:evc animated:YES];
        }
        if (indexPath.row==3) {
            WYIndustryController *ivc = [[WYIndustryController alloc]init];
            [self.navigationController pushViewController:ivc animated:YES];
            
        }
    }
    
    if (indexPath.section==1&&indexPath.row==0) {
        WEAKSELF
        [CZHAddressPickerView areaPickerViewWithProvince:self.province city:self.city area:self.area areaBlock:^(NSString *province, NSString *city, NSString *area) {
            // CZHStrongS elf(self);
            weakSelf.province = province;
            weakSelf.city = city;
            weakSelf.area = area;
            //weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@%@",province,city,area];
            [weakSelf editAddres];
        }];
    }
    
    if (indexPath.row==1&&indexPath.section==1) {
        self.datePicker.hidden = NO;
    }
    if (indexPath.row==2&&indexPath.section==1 ) {
        WYEnterPriserIntroductionController *pvc = [[WYEnterPriserIntroductionController alloc]init];
      //  pvc.textString = self.editMessage.companyIntro;
        pvc.introString = self.editMessage.companyIntro;
        [self.navigationController pushViewController:pvc animated:YES];
    }
    
    if (indexPath.section==4) {
         WYProductService *service = self.dataArray[indexPath.row];
        WYProductCell *cell = (WYProductCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        WYEditProductController *evc = [[WYEditProductController alloc]init];
        evc.service = service;
        evc.image = cell.productImageView.image;
        
        
        
        [self.navigationController pushViewController:evc animated:YES];
        
    }
    
    
}

-(void)editAddres
{
    WEAKSELF
    [WYHttpServer editComPanyAddressWithadddress:[NSString stringWithFormat:@"%@%@%@",self.province,self.city,self.area] SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }else{
            
        }
    }];
}
#pragma mark WYHonorCellDelegate
-(void)didChangeHeightWithHonor:(WYHonorCell *)cell
{
    [self.tableView reloadData];
}
-(void)didChangeHeight:(WYHonorCell *)cell
{
    [self.tableView reloadData];
}
-(UITableView *)tableView
{
    if (!_tableView) {
        CGRect frame = CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight-5);
        _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    }
    return _tableView;
}
#pragma mark  添加企业荣誉
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData * imageDate = UIImageJPEGRepresentation(photo, 0.1);
    UIImage *image = [UIImage imageWithData:imageDate];
    
    NSString *path = [image QCloudTempFilePathWithExtension:@"PNG"];
    self.pathString = path;
    [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
    //   [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    // [self showLoading:@""];
    WEAKSELF
    [WYHttpServer uploadImageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        WYUploadModel *model = [WYUploadModel getupLoadModelFromJson:response[@"result"]];
        [weakSelf upLoadWithPath:model.uploadUrl];
        weakSelf.model = model;
    }];
}
-(void)upLoadWithPath:(NSString *)path
{
    WEAKSELF
    [WYHttpServer PUTWithURLStr:path filePath:self.pathString SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            //  [MBProgressHUD hideHUDForView:self.view animated:YES];
            // [self hideLoading];
            //            [weakSelf editHeaderImageview];
            if (weakSelf.isLogo) {
                [weakSelf addLogo];
            }else{
                [weakSelf addHonor];
            }
            
        }else{
            //[weakSelf toast:errorMessage];
        }
        
    }];
}
-(void)addHonor
{
    [self.honorArray addObject:self.model.visitUrl];
    WEAKSELF
    [WYHttpServer addHonor:[self.honorArray componentsJoinedByString:@","] SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf toast:@"添加成功"];
            [weakSelf loadData];
        }else{
            [weakSelf toast:errorMessage];
        }
        
        
        
    }];
}
-(void)addLogo
{
     WEAKSELF
    [WYHttpServer addUserCompanyLogo:self.model.visitUrl SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }else{
            [weakSelf toast:errorMessage];
        }
        
        
    }];
    
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    }
}








@end
